package com.myFwk.config;

import com.myFwk.constant.Constants;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.RabbitConnectionFactoryBean;
import org.springframework.amqp.rabbit.connection.SimpleConnection;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.DirectMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * @Title:
 * @Description:
 * @Author: guowl
 * @version： 1.0
 * @Date:2021/10/21
 * @Copyright: Copyright(c)2021 RedaFlight.com All Rights Reserved
 */
//@Configuration
@Slf4j
public class RabbitConfig {


//    @Bean
    public DirectMessageListenerContainer setListenerContainer(ConnectionFactory connection) {
        DirectMessageListenerContainer containers = new DirectMessageListenerContainer(connection);
        containers.setQueueNames(Constants.QUEUE_FWK_0);
        containers.setExposeListenerChannel(true);
//        //设置最大并发数量
//
//        //设置最小并发数量
//
//        //设置手动确认模式
        containers.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        containers.setMessageListener(new ChannelAwareMessageListener() {
            @Override
            public void onMessage(Message message, Channel channel) throws Exception {
                /**通过basic.qos方法设置prefetch_count=1，这样RabbitMQ就会使得每个Consumer在同一个时间点最多处理一个Message，
                 换句话说,在接收到该Consumer的ack前,它不会将新的Message分发给它 */
                channel.basicQos(1);
                log.info("接收队列的消息：{}", new String(message.getBody()));
                /**为了保证永远不会丢失消息，RabbitMQ支持消息应答机制。
                 当消费者接收到消息并完成任务后会往RabbitMQ服务器发送一条确认的命令，然后RabbitMQ才会将消息删除。*/
                try {
                    /**
                     * 当消息确实失败 表示消息接收失败
                     */
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                } catch (Exception exception) {
                    log.error("消费消息确认失败:{}", exception.getMessage());
                }

            }
        });
        return containers;
    }
}
